// ProjectTable.tsx  
import React, { useEffect, useState } from 'react';
import { Table, notification } from 'antd';
import { fetchApi } from '../../general/api';

interface ProjectData {
    key: string;
    name: string;
    description: string;
}

interface ProjectTableProps {
    onRowClick?: (key: string) => void; // Define a prop for the click callback  
}

const ProjectTable: React.FC<ProjectTableProps> = ({ onRowClick }) => {
    const [dataSource, setDataSource] = useState<ProjectData[]>([]);
    const [loading, setLoading] = useState<boolean>(true);

    const fetchProjects = async () => {
        try {
            setLoading(true);
            const response = await fetchApi('/easymonitor/api/project');
            const projects = response.map((project: any, index: number) => ({
                key: project.project_id || index,
                name: project.project_name,
                description: project.description,
            }));
            setDataSource(projects);
            notification.success({
                message: '请求成功',
                description: '项目数据查询成功。',
                duration: 2,
            });
        } catch (error) {
            notification.error({
                message: '请求失败',
                description: '项目数据查询失败:' + error,
                duration: 2,
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchProjects();
    }, []);

    const columns = [
        {
            title: '项目',
            dataIndex: 'name',
            key: 'name',
            className: 'no-wrap',
        },
        {
            title: '备注',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true,
            className: 'no-wrap',
        },
    ];

    return (
        <Table
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            size="small"
            onRow={(record) => ({
                onClick: () => {
                    if (onRowClick) {
                        onRowClick(record.key); // Call the callback with the row key  
                    }
                },
            })}
            rowClassName="custom-table-row"
        />
    );
};

export default ProjectTable;